<template>
  <div class="default-main ba-table-box">
    <!-- 'inspection' -->
    <TableHeader
      :buttons="['refresh', 'comSearch', 'columnDisplay']"
      @action="baTable.onTableHeaderAction"
    />
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 初始化到活性炭监控表单 -->
    <Origin />
  </div>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, markRaw, onBeforeUnmount, inject } from "vue";
import { useLongRange } from "@/store/backend/DeviceM/longRange";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common";
import type { TableRow, TableColumn } from "@/utils/baTable";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { DeviceMAccess } from "@/api/backend/index";
import { useRegion } from "@/store/backend/SysM/region";
import { useRoute } from "vue-router";
import TagState from "@/components/dictTagState/index.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useAccess } from "@/store/backend/DeviceM/access";
import _ from "lodash";
import { ElMessageBox } from "element-plus";
import Origin from "./origin.vue";
import { useDeviceWarnSet } from "@/store/backend/DeviceM/warnSet";

const tableRef = ref();
const { proxy } = useCurrentInstance(); //全局事件总线
const region = useRegion();
const LR = useLongRange();
const route = useRoute();
const dictionary = useDictionary();
const access = useAccess();
const warnSet = useDeviceWarnSet();
const navTabs = inject("navTabs") as any;

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 字段显隐记忆功能 字段中有默认隐藏false情况的
const filedShowOffDefault = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(route.path + "/" + filter)
      ? true
      : false;
  }
  return "";
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      ? (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(DeviceMAccess), //this.api = api菜单管理相关
  {
    pk: "id", //设备id
    column: [
      { type: "selection", align: "center", operator: false },
      // { label: "ID", prop: "id", align: "center", width: 50, operator: false },
      {
        show: filedShowOff("gatewaycode"),
        label: "网关编号",
        prop: "gatewaycode",
        align: "center",
      },
      {
        show: filedShowOff("code"),
        label: "设备编号",
        prop: "code",
        align: "center",
      },
      {
        show: filedShowOff("name"),
        label: "设备名称",
        prop: "name",
        align: "center",
      },
      {
        show: filedShowOff("cname"),
        label: "企业名称",
        prop: "cname",
        align: "center",
      },
      {
        show: filedShowOff("state"),
        label: "设备状态",
        prop: "state",
        align: "center",
        width: "90",
        render: "customRender",
        customRender: markRaw(TagState),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show:
          filedShowOffDefault("openState") === ""
            ? false //默认false
            : filedShowOffDefault("openState"),
        label: "设备启停",
        prop: "openState",
        align: "center",
        render: "switchAccess",
        replaceValue: {
          0: "停",
          1: "启",
        },
        operator: false,
      },
      {
        show: operatorShowOff([route.path + "/edit"]),
        label: "操作",
        align: "center",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "longRange",
            title: "指令",
            text: "",
            type: "primary",
            icon: "iconfont icon-tianchong",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "origin",
            title: "活性炭监控初始化",
            text: "",
            type: "primary",
            icon: "iconfont icon-xitongchushihua",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      regions: region.regionIds + "",
      pageSize: pageSizeKeep(),
    },
  },
  {
    defaultItems: {},
  }
);

const emit = defineEmits(["on-showLongRangeList", "on-showWarnList"]);
//获取设备的指令配置列表信息
const devicesLongRange = (name: string, row: anyObj) => {
  //将row数据传递给指令配置类表表单
  emit("on-showLongRangeList", row);
  LR.$state.id = row.id;
  proxy.eventBus.emit("changLRId", row.id);
};
//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

//打开初始化表单
const originButtonClick = (name: string, row: anyObj, realObj: anyObj) => {
  //打开初始化表单
  baTable.form.operate = name;
  // let temp = {
  //   ecode: row.code,
  //   eid: row.id,
  //   pressureValue: realObj.pressureValue,
  //   criticalValue: realObj.criticalValue,
  //   lifeValue: realObj.lifeValue,
  //   prompt: realObj.prompt,
  //   type: realObj.type,
  //   usernum: realObj.usernum,
  //   repalcenum: realObj.repalcenum,
  // };
  let temp = {};
  if (JSON.stringify(realObj) === "{}") {
    temp = {
      ecode: row.code,
      eid: row.id,
      pressureValue: "",
      criticalValue: "",
    };
  } else {
    temp = {
      ecode: row.code,
      eid: row.id,
      pressureValue: realObj.pressureValue,
      criticalValue: realObj.criticalValue,
      lifeValue: realObj.lifeValue,
      prompt: realObj.prompt,
      type: realObj.type,
      usernum: realObj.usernum,
      repalcenum: realObj.repalcenum,
    };
  }
  access.item = row;
  let obj = _.cloneDeep(row);
  // obj.state = 1; //改为在线数据
  obj.estate = 0; //运行状态改为异常
  access.item = obj;
  console.log("access.item", access.item, temp);
  baTable.form.items = Object.assign(baTable.form.items, temp);
};

//获取设备的告警配置列表信息
const deviceWarnSet = (name: string, row: anyObj) => {
  //将row数据传递给告警配置类表表单
  emit("on-showWarnList", row);
  warnSet.$state.id = row.id;
  proxy.eventBus.emit("changeWarnId", row.id);
};

//刷新表单
proxy.eventBus.on("afterOrderRefresh", () => {
  baTable.getList(DeviceMAccess);
});

onMounted(() => {
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  //   console.log("tableRef.value", tableRef.value);
  baTable.mount();
  baTable.getList(DeviceMAccess);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //点击获取该设备的指令列表
      if (data.name == "longRange") {
        devicesLongRange(data.name, data.row);
        //点击获取该设备的告警列表
        deviceWarnSet(data.name, data.row);
      } else if (data.name == "origin") {
        console.log("初始化", data.row);
        //在初始化之前判断是否含有数据，有数据就提示无法多次初始化 数据为空打开表单
        access
          .getDetail(data.row.id)
          .then((res: any) => {
            console.log("获取的数据", res);
            if (res.rows.length !== 0) {
              //   ElMessageBox.confirm("设备已初始化完成,无法再次初始化", "提示", {
              //     confirmButtonText: "确认",
              //     cancelButtonText: "取消",
              //     type: "warning",
              //   });
              originButtonClick(data.name, data.row, res.rows[0]);
            } else {
              originButtonClick(data.name, data.row, {});
            }
          })
          .catch((err) => {});
      }
    }
  );
});

onBeforeUnmount(() => {
  proxy.eventBus.off("afterOrderRefresh");
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped></style>
